package cn.tedu.foreign.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@RestController
public class RandomController {
    private static String line = "abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /**
     *响应一张二维码图片给客户端
     */
    @RequestMapping("/random.jpg")
    public void createRandomImage(HttpSession session, HttpServletResponse response) {
        response.setContentType("image/jpeg");

        //1创建一张空白图片，同时指定宽高   理解为:搞一张白纸，准备画画
        BufferedImage image = new BufferedImage(
                85, 50, BufferedImage.TYPE_INT_RGB
        );

        //2通过图片获取绘制该图片的画笔，通过这个画笔就可以往该图片上绘制了
        Graphics g = image.getGraphics();

        Random random = new Random();
        //3随机生成个颜色涂满整张画布
        Color color = new Color(
                random.nextInt(256),
                random.nextInt(256),
                random.nextInt(256));
        g.setColor(color);//设置画笔颜色
        g.fillRect(0, 0, 85, 50);
        StringBuilder rand = new StringBuilder();
        //4向画布上绘制文字

        g.setFont(new Font(null, Font.BOLD, 30));
        for (int i = 0; i < 4; i++) {
            color = new Color(
                    random.nextInt(256),
                    random.nextInt(256),
                    random.nextInt(256));
            g.setColor(color);//设置画笔颜色
            String str = line.charAt(random.nextInt(line.length())) + "";
            rand.append(str);
            g.drawString(str, i * 15 + 8, 30 + random.nextInt(11) - 5);
        }

        //5随机生成5条干扰线
        for (int i = 0; i < 5; i++) {
            color = new Color(
                    random.nextInt(256),
                    random.nextInt(256),
                    random.nextInt(256));
            g.setColor(color);//设置画笔颜色
            g.drawLine(random.nextInt(71), random.nextInt(31),
                    random.nextInt(71), random.nextInt(31));
        }


        try {
            ImageIO.write(image, "jpg",
                    response.getOutputStream());
            System.out.println("图片已生成");
        } catch (IOException e) {
            e.printStackTrace();
        }
        session.setAttribute("random",rand.toString().trim());
    }
    @RequestMapping("random")
    /**
     * 取出之前请求时的二维码字符串返回给客户端
     */
    public String random(HttpSession session){
        return (String) session.getAttribute("random");
    }
}
